package com.doyens.cart.interceptor;

import com.doyens.auth.entity.UserInfo;
import com.doyens.auth.utils.CookieUtils;
import com.doyens.auth.utils.JwtUtils;
import com.doyens.cart.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties jwtProperties;

    private static final  ThreadLocal<UserInfo>  THREAD_LOCAL = new ThreadLocal<>();
    //进入controller之前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //获取cookie中的token
        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        //解析token,获取用户信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
        if (userInfo == null){
            return false;
        }
        THREAD_LOCAL.set(userInfo);
        //用户量比较大, 数据安全的问题
        return true;
    }

    //执行完controller之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空局部变量
        THREAD_LOCAL.remove();
    }

    //获取UserInfo对象
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

}
